// import { login, logout, getInfo } from '@/api/user'
import { login, logout, getUserInfo } from '@/api/job'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const phone = userInfo.phone
    const  password  = userInfo.password
    return new Promise((resolve, reject) => {
      login(  phone.trim(),  password ).then(response => {
        console.log("res", response)
        const data  = response.data.token
        console.log(3333, data)
        commit('SET_TOKEN', data)
        setToken(data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(response => {
        // console.log("getInfo接收到的response", response)
        const { data } = response
        console.log("getInfo接收到的token", data)
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        const  username  = data.userInfo.username
        const userId = data.userInfo.id
        localStorage.setItem("username",username)
        localStorage.setItem("userId",userId)
        // console.log("getInfo接收到的username", username)
        console.log("getInfo接收到的id", userId)
        commit('SET_NAME', username)
        commit('SET_NAME', userId)
        commit('SET_AVATAR', "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png")
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        localStorage.removeItem("username")
        localStorage.removeItem("userId")
        console.log("退出以后localStorage.getItem",localStorage.getItem)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

